<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;

/**
 * 分期商品发货任务表
 *
 * @icon fa fa-circle-o
 */
class Deliverytask extends Backend
{
 
	
	protected $relationSearch = true;
    /**
     * DeliveryTask模型对象
     * @var \app\common\model\DeliveryTask
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\DeliveryTask;

        $config = [
            'statusList' => \app\common\model\DeliveryTask::$statusList
        ];
        
        $this->assign($config);
        $this->assignconfig($config);
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
	
	
	/**
	 * 查看
	 */
	public function index()
	{
		//设置过滤方法
		$this->request->filter(['strip_tags']);
		if ($this->request->isAjax()) {
			//如果发送的来源是Selectpage，则转发到Selectpage
			if ($this->request->request('keyField')) {
				return $this->selectpage();
			}
			list($where, $sort, $order, $offset, $limit) = $this->buildparams();
			
			
			$with = ['user', 'orderGoods'];
			$total = $this->model
				->with($with)
				->where($where)
				->order($sort, $order)
				->count();
			
			$list = $this->model
				->with($with)
				->where($where)
				->order($sort, $order)
				->limit($offset, $limit)
				->select();
			
			$list = collection($list)->toArray();
			$result = array("total" => $total, "rows" => $list);
			
			return json($result);
		}
		return $this->view->fetch();
	}
	
	/**
	 * 发货
	 */
	public function ship($ids = null)
	{
		$row = $this->model->alias('t')
			->join('order o', 't.order_id = o.id', 'left')
			->join('user u', 'o.user_id = u.id', 'left')
			->join('business b', 'o.business_id = b.id', 'left')
			->join('order_address a', 'o.id = a.order_id', 'left')
			->join('shipping s', 'o.shipping_id = s.id', 'left')
			->join('area p', 'a.province_id = p.id', 'left')
			->join('area c', 'a.city_id = c.id', 'left')
			->join('area ar', 'a.area_id = ar.id', 'left')
			->where(['t.id' => $ids])
			->field('o.*, u.username, a.recipients, a.mobile, a.address, p.areaname as pname, c.areaname as cname, ar.areaname as aname, a.province_id, a.city_id, a.area_id, b.name as bname, s.name as shipping_name, o.order_prom_type, t.status, t.order_goods_id')
			->find();
		if (!$row) {
			$this->error(__('No Results were found'));
		}
		
		if($row['status'] != \app\common\model\DeliveryTask::STATUS_ING) {
			$this->error('该任务已经完成');
		}
		
		$goods = Db::name('orderGoods')
			->where(['id' => $row['order_goods_id']])
			->select();
		
		
		$adminIds = $this->getDataLimitAdminIds();
		if (is_array($adminIds)) {
			if (!in_array($row[$this->dataLimitField], $adminIds)) {
				$this->error(__('You have no permission'));
			}
		}
		if ($this->request->isPost()) {
			$params = $this->request->post("row/a");
			if ($params) {
				Db::startTrans();
				try {
					
					if(!$params['shipping_code']){
						throw new Exception('请填写物流单号');
					}
					
					$shipping = Db::name('shipping')->find($params['shipping_id']);
					
					$data = [
						'order_id' => $row['id'],
						'order_goods_ids' => $row['order_goods_id'],
						'shipping_id' => $params['shipping_id'],
						'shipping_code' => $shipping['code'],
						'shipping_no' => $params['shipping_code'],
						'create_time' => time(),
						'update_time' => time()
					];
					
					$result = Db::name('orderShipping')->insert($data);
					if ($result === false) {
						throw new Exception($row->getErrot());
					}
					
					//如果为分期商品，更改分期商品发货任务
					$taskModel = new \app\common\model\DeliveryTask();
					$where['order_id'] = $row['id'];
					$task = Db::name('deliveryTask')->where($where)->find();
					
					$number = $task['delivery_number'] + 1;
					$taskData = [
						'delivery_number' => $number,
						'next_time' => strtotime('+'.$task['days'].' days')
					];
					
					if($number == $task['need_number']) {
						$data['status'] = $taskModel::STATUS_F;
					}
					
					$taskRes = $taskModel->save($taskData, $where);
					
					if(!$taskRes) {
						throw new Exception('更改分期发货任务出错');
					}
					
					Db::commit();
					$this->success();
				} catch (Exception $e) {
					Db::rollback();
					$this->error($e->getMessage());
				}
			}
			$this->error(__('Parameter %s can not be empty', ''));
		}
		
		$shippings = Db::name('shipping')->field('id,name')->order(['name' => 'asc'])->select();
		return $this->view->fetch('ship', [
			'row' => $row,
			'goods' => $goods,
			'shippings' => $shippings,
		]);
	}
	
}
